//给你一个二叉搜索树的根节点 root ，返回 树中任意两不同节点值之间的最小差值 。 
//
// 差值是一个正数，其数值等于两值之差的绝对值。 
//
// 
//
// 示例 1： 
// 
// 
//输入：root = [4,2,6,1,3]
//输出：1
// 
//
// 示例 2： 
// 
// 
//输入：root = [1,0,48,null,null,12,49]
//输出：1
// 
//
// 
//
// 提示： 
//
// 
// 树中节点的数目范围是 [2, 10⁴] 
// 0 <= Node.val <= 10⁵ 
// 
//
// 
//
// 注意：本题与 783 https://leetcode-cn.com/problems/minimum-distance-between-bst-
//nodes/ 相同 
//
// Related Topics 树 深度优先搜索 广度优先搜索 二叉搜索树 二叉树 👍 473 👎 0


package leetcode.editor.cn;

// [530]二叉搜索树的最小绝对差

public class MinimumAbsoluteDifferenceInBst_530 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        Solution solution = new MinimumAbsoluteDifferenceInBst_530().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        private class Info {
            int min;
            int max;
            int ans;

            public Info(int min, int max, int ans) {
                this.min = min;
                this.max = max;
                this.ans = ans;
            }

            public Info() {
            }
        }

        public int getMinimumDifference(TreeNode root) {
            if (root == null) {
                return 0;
            }
            return run(root).ans;
        }

        public Info run(TreeNode node) {
            if (node == null) {
                return null;
            }
            Info l = run(node.left);
            Info r = run(node.right);
            int min = node.val;
            int max = node.val;
            int ans = Integer.MAX_VALUE;
            if (l != null) {
                min = l.min;
                ans = Math.min(ans, getSub(l.max, node.val));
                ans = Math.min(ans, l.ans);
            }
            if (r != null) {
                max = r.max;
                ans = Math.min(ans, getSub(r.min, node.val));
                ans = Math.min(ans, r.ans);
            }
            return new Info(min, max, ans);
        }

        public int getSub(int a, int b) {
            return Math.abs(a - b);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}